package com.lujieni.test.testechoserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.StandardCharsets;

public class Server {

    public static void main(String[] args) {

        //使用ServerBootstrap启动服务
        ChannelFuture cf = new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                // 将msg转为ByteBuf
                                ByteBuf bb = (ByteBuf) msg;
                                System.out.println(bb.toString(StandardCharsets.UTF_8));
                                //ByteBuf response = ctx.alloc().buffer(); // 建议使用 ctx.alloc() 创建 ByteBuf
                                //response.writeBytes(bb);
                                ctx.writeAndFlush(bb);
                            }
                        });
                    }
                })
                .bind(8081);


    }


}
